package cn.tedu.superscholarstore.service.impl;

import cn.tedu.superscholarstore.ex.ServiceException;
import cn.tedu.superscholarstore.mapper.FavoritesMapper;
import cn.tedu.superscholarstore.pojo.vo.FavoritesVo;
import cn.tedu.superscholarstore.pojo.vo.UserVO;
import cn.tedu.superscholarstore.service.FavoritesService;
import cn.tedu.superscholarstore.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 收藏的service实现类
 */
@Slf4j
@Service
public class FavoritesImpl  implements FavoritesService {

    @Autowired
    FavoritesMapper mapper;

    public FavoritesImpl() {
      log.debug("创建业务处理对象: FavoritesImpl");
    }


    @Override
    public List<FavoritesVo> list(HttpSession session) {
        log.debug("开始处理[获取收藏列表]业务,参数为{}",session);
        UserVO vo = (UserVO) session.getAttribute("user");
        if(vo==null){
           String message =("获取失败,请先登录!");
           log.debug(message);
           throw  new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        log.debug("已登录,准备查询数据");
        return mapper.list(vo.getId());
    }

    @Override
    public Integer countByUserId(HttpSession session) {
        log.debug("开始处理[获取收藏数量]业务,参数为{}",session);
        UserVO vo = (UserVO) session.getAttribute("user");
        if(vo==null){
            String message =("获取失败,请先登录!");
            log.debug(message);
            throw  new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        log.debug("已登录,准备查询数据");
        return mapper.countByUserId(vo.getId());
    }

    @Override
    public List<FavoritesVo> selectByLim(int index, HttpSession session) {
        log.debug("开始处理[分页查询]业务,参数为{}",session);
        UserVO vo = (UserVO) session.getAttribute("user");
        if(vo==null){
            String message =("获取失败,请先登录!");
            log.debug(message);
            throw  new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        log.debug("已登录,准备查询数据");
        int i = (index-1)*12;
        List<FavoritesVo> favoritesVos = mapper.selectByLim(i,vo.getId());
        return favoritesVos;
    }

    @Override
    public void deleteById(int id) {
        log.debug("开始处理[删除收藏]业务,参数为{}",id);
        int delete = mapper.delete(id);
        if(delete!=1){
            String message =("删除失败,服务器忙!");
            log.debug(message);
            throw  new ServiceException(ServiceCode.ERR_BAD_REQUEST,message);
        }
    }
}
